package com.b2b.controller.system;

import com.b2b.model.AdminLogin;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.b2b.exception.CustomException;
import com.b2b.exception.CustomUnauthorizedException;
import com.b2b.model.SystemAdministratorDto;
import com.b2b.model.common.BaseDto;
import com.b2b.model.common.ResponseBean;
import com.b2b.service.SystemAdministratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/systemAdministrator")
@PropertySource("classpath:config.properties")
public class SystemAdministratorController {

    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    private final SystemAdministratorService systemAdministratorService;

    @Autowired
    public SystemAdministratorController(SystemAdministratorService systemAdministratorService){
        this.systemAdministratorService = systemAdministratorService;
    }

    @PostMapping("/add")
    public ResponseBean add(@RequestBody SystemAdministratorDto systemAdministratorDto){
        SystemAdministratorDto systemAdministratorDtoTemp = new SystemAdministratorDto();
        systemAdministratorDtoTemp.setUserName(systemAdministratorDto.getUserName());
        Integer count = systemAdministratorService.selectCount(systemAdministratorDtoTemp);
        if (count > 0 ){
            throw new CustomUnauthorizedException("该名称已存在(Account exist.)");
        }
        count = systemAdministratorService.insert(systemAdministratorDto);
        if (count <= 0 ){
            throw new CustomException("新增失败(Insert Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", systemAdministratorDto);
    }

    @PostMapping("/login")
    public ResponseBean login(@RequestBody SystemAdministratorDto systemAdministratorDto){
        String username = systemAdministratorDto.getUserName();
        SystemAdministratorDto systemAdministratorDtoTemp = new SystemAdministratorDto();
        systemAdministratorDtoTemp.setUserName(username);
        Integer count = systemAdministratorService.selectCount(systemAdministratorDtoTemp);
        if (count <= 0){
            throw new CustomException("账号密码错误(Login Failure)");
        }

        systemAdministratorDtoTemp = systemAdministratorService.selectOne(systemAdministratorDtoTemp);
        if (!systemAdministratorDtoTemp.getPassword().equals(systemAdministratorDto.getPassword())){
            throw new CustomException("账号密码错误(Login Failure)");
        }
        AdminLogin adminLogin = new AdminLogin();
        adminLogin.setUserInfo(systemAdministratorDtoTemp);
        String[] permsList = new String[]{
                "/Welcome",
                "/CommodityList",
                "/CommodityExam",
                "/Transaction",
                "/Inquiry",
                "/Bidding",
                "/AfterSaleList",
                "/Template",
                "/Sale",
                "/Visit",
                "/StoreAudit",
                "/Person",
                "/Enterprise",
                "/Users",
                "/Kind",
                "/UserRouter",
                "/UserApi",
                "/Administrator",
                "/Intervention",
                "/Advertise"
        };
        adminLogin.setPerms(permsList);
        return new ResponseBean(HttpStatus.OK.value(), "登录成功(Login Success)", adminLogin);
    }

    @GetMapping("/byId")
    public ResponseBean get(@RequestBody SystemAdministratorDto systemAdministratorDto){
        systemAdministratorDto = systemAdministratorService.selectOne(systemAdministratorDto);
        if (systemAdministratorDto.getPassword() == null){
            throw new CustomUnauthorizedException("该名称不存在(Account not exist.)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Select Success)", systemAdministratorDto);
    }

    @GetMapping("/get")
    public ResponseBean getAll(BaseDto baseDto){
        if (baseDto.getPage() == null || baseDto.getRows() == null) {
            baseDto.setPage(1);
            baseDto.setRows(10);
        }
        PageHelper.startPage(baseDto.getPage(), baseDto.getRows());
        List<SystemAdministratorDto> systemAdministratorDtos = systemAdministratorService.selectAll();
        PageInfo<SystemAdministratorDto> selectPage = new PageInfo<SystemAdministratorDto>(systemAdministratorDtos);
        if (systemAdministratorDtos == null || systemAdministratorDtos.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("count", selectPage.getTotal());
        result.put("data", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    @PutMapping("/update")
    public ResponseBean update(@RequestBody SystemAdministratorDto systemAdministratorDto){
        SystemAdministratorDto systemAdministratorDtoTemp = new SystemAdministratorDto();
        systemAdministratorDtoTemp.setAdminId(systemAdministratorDto.getAdminId());
        Integer count = systemAdministratorService.selectCount(systemAdministratorDtoTemp);
        if (count <= 0 ){
            throw new CustomUnauthorizedException("该账号不存在(Account Not exist.)");
        }
        systemAdministratorDtoTemp.setRoleId(systemAdministratorDto.getRoleId());
        count = systemAdministratorService.updateByPrimaryKeySelective(systemAdministratorDtoTemp);
        if (count <= 0) {
            throw new CustomException("更新失败(Update Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update Success)", null);
    }

    @DeleteMapping("/delete")
    // @RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
    public ResponseBean delete(@RequestBody SystemAdministratorDto systemAdministratorDto) {
        SystemAdministratorDto systemAdministratorDtoTemp = new SystemAdministratorDto();
        systemAdministratorDtoTemp.setAdminId(systemAdministratorDto.getAdminId());
        Integer count = systemAdministratorService.selectCount(systemAdministratorDtoTemp);
        if (count <= 0 ){
            throw new CustomUnauthorizedException("该账号不存在(Account Not exist.)");
        }
        count = systemAdministratorService.deleteByPrimaryKey(systemAdministratorDto.getAdminId());
        if (count <= 0) {
            throw new CustomException("删除失败，ID不存在(Deletion Failed. ID does not exist.)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "删除成功(Delete Success)", null);
    }
}
